import json
import os
from typing import List, Dict, Tuple
import random

class DialogueSystem:
    """对话系统，处理游戏中的NPC对话和对话逻辑"""
    
    def __init__(self, dialogue_dir: str = "../../数据管理/narrative_archive/dialogues"):
        """初始化对话系统"""
        self.dialogue_dir = dialogue_dir
        os.makedirs(self.dialogue_dir, exist_ok=True)
        self.dialogues = {}  # 存储对话数据: {角色ID: {对话ID: 对话内容}}
        self.load_all_dialogues()
    
    def load_all_dialogues(self):
        """加载所有角色的对话数据"""
        for filename in os.listdir(self.dialogue_dir):
            if filename.endswith(".json"):
                character_id = os.path.splitext(filename)[0]
                self.load_character_dialogues(character_id)
    
    def load_character_dialogues(self, character_id: str) -> bool:
        """加载特定角色的对话数据"""
        dialogue_file = os.path.join(self.dialogue_dir, f"{character_id}.json")
        if not os.path.exists(dialogue_file):
            return False
        
        try:
            with open(dialogue_file, "r", encoding="utf-8") as f:
                self.dialogues[character_id] = json.load(f)
            return True
        except Exception as e:
            print(f"加载角色 {character_id} 的对话失败: {str(e)}")
            return False
    
    def save_character_dialogues(self, character_id: str):
        """保存特定角色的对话数据"""
        if character_id not in self.dialogues:
            return False
        
        dialogue_file = os.path.join(self.dialogue_dir, f"{character_id}.json")
        try:
            with open(dialogue_file, "w", encoding="utf-8") as f:
                json.dump(self.dialogues[character_id], f, ensure_ascii=False, indent=2)
            return True
        except Exception as e:
            print(f"保存角色 {character_id} 的对话失败: {str(e)}")
            return False
    
    def add_dialogue(self, character_id: str, dialogue_id: str, dialogue: Dict):
        """添加对话内容"""
        if character_id not in self.dialogues:
            self.dialogues[character_id] = {}
        
        # 对话格式: {
        #   "text": "对话文本",
        #   "conditions": {"变量1": 值1, ...},  # 触发条件
        #   "responses": ["回应1", "回应2"],    # 玩家可选回应
        #   "next": "下一个对话ID"             # 下一段对话
        # }
        self.dialogues[character_id][dialogue_id] = dialogue
        self.save_character_dialogues(character_id)
    
    def get_dialogue(self, character_id: str, dialogue_id: str, game_state: Dict = None) -> Dict:
        """获取符合条件的对话"""
        if character_id not in self.dialogues:
            if not self.load_character_dialogues(character_id):
                return {"text": f"[{character_id} 没有对话数据]"}
        
        if dialogue_id not in self.dialogues[character_id]:
            return {"text": f"[{character_id} 没有 {dialogue_id} 对话]"}
        
        dialogue = self.dialogues[character_id][dialogue_id].copy()
        
        # 检查条件是否满足
        if "conditions" in dialogue and game_state:
            conditions_met = True
            for cond_key, cond_value in dialogue["conditions"].items():
                if game_state.get(cond_key) != cond_value:
                    conditions_met = False
                    break
            
            if not conditions_met:
                # 如果条件不满足，返回默认对话或随机对话
                if "fallback" in dialogue:
                    return self.get_dialogue(character_id, dialogue["fallback"], game_state)
                else:
                    return self.get_random_dialogue(character_id, game_state)
        
        return dialogue
    
    def get_random_dialogue(self, character_id: str, game_state: Dict = None) -> Dict:
        """获取随机对话"""
        if character_id not in self.dialogues:
            if not self.load_character_dialogues(character_id):
                return {"text": f"[{character_id} 没有对话数据]"}
        
        dialogue_ids = list(self.dialogues[character_id].keys())
        if not dialogue_ids:
            return {"text": f"[{character_id} 没有对话数据]"}
        
        # 随机选择一个对话
        return self.get_dialogue(character_id, random.choice(dialogue_ids), game_state)
    
    def start_conversation(self, character_id: str, start_dialogue_id: str = "greeting", game_state: Dict = None) -> List[Dict]:
        """开始一段对话流程"""
        conversation = []
        current_dialogue_id = start_dialogue_id
        
        while current_dialogue_id:
            dialogue = self.get_dialogue(character_id, current_dialogue_id, game_state)
            conversation.append({
                "character": character_id,
                "dialogue_id": current_dialogue_id,
                "text": dialogue.get("text", ""),
                "responses": dialogue.get("responses", [])
            })
            
            # 如果有玩家回应选项，等待玩家选择
            if dialogue.get("responses"):
                break
                
            current_dialogue_id = dialogue.get("next")
        
        return conversation